package com.yi.wood.web.socket;

import com.yi.wood.service.po.UserCachePo;
import com.yi.wood.utils.StringTokenUtil;
import com.yi.wood.web.util.UserCacheUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by moyi on 2019/2/18 10:09
 *
 * @author moyi
 */
@Log4j2
@ServerEndpoint(value = "/ws/{sid}")
@Component
public class SystemWebSocket {

    private static UserCacheUtil userCacheUtil;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentMap<String, Session> sessionConcurrentMap = new ConcurrentHashMap<>();

    public static void setUserCacheUtil(UserCacheUtil userCacheUtil) {
        SystemWebSocket.userCacheUtil = userCacheUtil;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) throws IOException {
        if (StringUtils.isEmpty(sid)){
            session.close();
            return;
        }
        UserCachePo userCachePo = userCacheUtil.getUserByCache(StringTokenUtil.unPrefix(sid));
        if (Objects.isNull(userCachePo)){
            session.close();
            return;
        }
        log.info("上线userInfo = {}",userCachePo.toString());
        sessionConcurrentMap.put(sid, session);
    }

    @OnClose
    public void onClose(Session session, @PathParam("sid") String sid){
        log.info("下线id = {}", sid);
        sessionConcurrentMap.remove(sid);
    }

    @OnMessage
    public void onMsg(String message, Session session){
        log.info("消息msg = {}",message);
        sendGroup(message);
    }

    @OnError
    public void onError(Session session, Throwable error){
        log.info("error = {}",error.getMessage());
        error.printStackTrace();
    }

    /**
     * 主动关闭连接
     * @param sid 连接ID
     * @throws IOException 异常
     */
    public void kill(String sid) throws IOException {
        Session session = sessionConcurrentMap.get(sid);
        if (!Objects.isNull(session)){
            session.close();
            sessionConcurrentMap.remove(sid);
        }
    }

    /**
     * 发送消息
     * @param sid ID
     * @param msg 消息
     * @throws IOException 异常
     */
    public void sendMsg(String sid,String msg) throws IOException {
        Session session = sessionConcurrentMap.get(sid);
        if (!Objects.isNull(session)){
            session.getBasicRemote().sendText(msg);
        }
    }


    public void sendGroup(String msg){
        sessionConcurrentMap.values().forEach(session -> {
            try {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 获取在线的数量
     * @return 数量
     */
    public int getOnlineCount(){
        return sessionConcurrentMap.size();
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    public static ConcurrentMap<String, Session> getSessionConcurrentMap() {
        return sessionConcurrentMap;
    }
}
